package p.ithorns.sample.office.pdf;

import io.woo.htmltopdf.HtmlToPdf;
import io.woo.htmltopdf.HtmlToPdfObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * RenderController
 * <p>
 * 使用TemplateEngine将Thymeleaf模板渲染为HTML
 *
 * @author HtL
 * @date 2025/3/26 17:25
 * @since 1.0.0
 */
@RestController
public class RenderController {

    @Autowired
    private TemplateEngine templateEngine;

    record HotResource(String name, String id, String desc) {
    }

    @GetMapping("/html")
    public String saveHtmlToFile() {
        HotResource hotResource = new HotResource("热点资源1", "12345", "67890");
        Map<String, Object> variables = new HashMap<>();
        variables.put("hotSrc", hotResource);
        String renderedHtml = renderHtml("html-tpl.html", variables);
        testHtmltopdf(renderedHtml);
        // saveHtmlToFile(renderedHtml, "file.html");
        return "HTML file saved successfully!";
    }

    void testHtmltopdf(String html) {
        HtmlToPdfObject htmlToPdfObject = HtmlToPdfObject.forHtml(html);
        HtmlToPdf.create()
                .object(htmlToPdfObject)
                .convert("output.pdf");
    }

    void saveHtmlToFile(String htmlContent, String filePath) throws IOException {
        FileWriter fileWriter = new FileWriter(filePath);
        fileWriter.write(htmlContent);
        fileWriter.close();
    }


    public String renderHtml(String templateName, Map<String, Object> variables) {
        // 创建一个上下文对象
        Context context = new Context();
        // 将传递的变量设置到上下文
        context.setVariables(variables);
        // 渲染指定模板为字符串
        return templateEngine.process(templateName, context);
    }

}